//
//  YWQrcodeManager.m
//  maintain
//
//  Created by Kyo on 16/3/16.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWQrcodeManager.h"
#import "MJExtension.h"
#import "UIColor+CustomColors.h"
#import "WMHttpTool.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "MBProgressHUD.h"
#import "YWQrcodeData.h"
#import "YWBuildingManager.h"
#import "YWEquipmentManager.h"
#import "QRCodeReaderViewController.h"
#import "YWNavigationController.h"
#import "YWScanEquipmentNotMatchVC.h"
#import "YWMeterReadingManager.h"
#import "YWBuildingJson.h"

@interface YWQrcodeManager ()
@property (nonatomic, strong) MBProgressHUD* HUD;
@end

@implementation YWQrcodeManager
YWSingletonM(Manager)

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = @"加载中";
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        [[UIApplication sharedApplication].keyWindow addSubview:hud];
        _HUD = hud;
    }
    return _HUD;
}

-(void)clickScanButtonWithType:(YWQrcodeScanType)scanType ViewController:(UIViewController *)vieController completionBlock:(QRCodeReaderCompletionBlock)completionBlock{
    QRCodeReaderViewController* reader = [[QRCodeReaderViewController alloc] init];
    reader.title = @"扫一扫";
    __weak __typeof(reader) weakReader = reader;
    //YWWeakSelf(weakSelf);
    [reader setCompletionWithBlock:^(NSString* resultAsString) {
        __strong __typeof(&*weakReader) strongReader = weakReader;
        resultAsString = [YWCommonTool realqrCodeIdWithqrCodeIdString:resultAsString];
        if ([YWCommonTool isEwinQrcode:resultAsString]){
            BOOL hasEquipment = YES;
            if (scanType == YWQrcodeScanTypeNomall) {
                hasEquipment = [[YWEquipmentManager shareManager] isExistEquipmentWithQrcodeId:resultAsString];
            }else if (scanType == YWQrcodeScanTypeMeterReading) {
                YWEquipment* equipment = [[YWMeterReadingManager shareManager] meterQRCoder:resultAsString];
                hasEquipment = equipment ? YES:NO;
            }
            if (!hasEquipment) {
                dispatch_async(dispatch_get_main_queue(), ^{[self.HUD show:YES];});
                [[YWQrcodeManager shareManager] requestQrcodeDataWithQrcodeId:resultAsString WithComplete:^(YWQrcodeRequestStatu requestStatu) {
                    dispatch_async(dispatch_get_main_queue(), ^{[self.HUD hide:YES];});
                    if (requestStatu == YWQrcodeRequestStatuSuccess) {
                        //扫描成功
                        if (completionBlock) {
                            completionBlock(resultAsString,strongReader);
                        }
                    }else{
                        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
                        senmVC.showContent = requestStatu == YWQrcodeRequestStatuNoData ? NSLocalizedString(kTextNoEquipment, nil):NSLocalizedString(kTextLoadFailed, nil);
                        [strongReader.navigationController pushViewController:senmVC animated:YES];
                    }
                }];
            }else{
                //扫描成功
                if (completionBlock) {
                    completionBlock(resultAsString,strongReader);
                }
            }
        }else{
            YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
            senmVC.showContent = @"非法二维码";
            [strongReader.navigationController pushViewController:senmVC animated:YES];
        }
        
    }];
    
    YWNavigationController* nav = [[YWNavigationController alloc] initWithRootViewController:reader];
    [vieController presentViewController:nav animated:YES completion:nil];
}

-(void)clickMaterialScanWithType:(YWQrcodeScanType)scanType ViewController:(UIViewController *)vieController completionBlock:(QRCodeReaderCompletionBlock)completionBlock{
    QRCodeReaderViewController* reader = [[QRCodeReaderViewController alloc] init];
    reader.title = @"扫一扫";
    __weak __typeof(reader) wReader = reader;
    //    YWWeakSelf(weakSelf);
    [reader setCompletionWithBlock:^(NSString* resultAsString) {
        //扫描成功
        if (completionBlock) {
            completionBlock(resultAsString,wReader);
        }
        
    }];
    
    YWNavigationController* nav = [[YWNavigationController alloc] initWithRootViewController:reader];
    [vieController presentViewController:nav animated:YES completion:nil];
}

-(void)requestQrcodeDataWithQrcodeId:(NSString *)qrcodeId WithComplete:(void (^)(YWQrcodeRequestStatu))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(YWQrcodeRequestStatuFail);}return;}
    
    NSDictionary* params = @{@"qrcodeId" : qrcodeId?:@"" };
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getQrcodeDataUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        YWQrcodeData* qrcodeData = [YWQrcodeData mj_objectWithKeyValues:json];
        if (qrcodeData) {
            if (qrcodeData.building) {
                [[YWBuildingManager shareManager] updatebuildingJsonWithArray:@[qrcodeData.building]];
            }
            if (qrcodeData.equipments.count) {
                [qrcodeData.equipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
                    equipment.buildingId = qrcodeData.building.buildingId;
                    equipment.apartmentId = qrcodeData.apartment.apartmentId;
                    equipment.floorId = qrcodeData.floor.floorId;
                    equipment.locationId = qrcodeData.location.locationId;
                    equipment.qrcodeId = qrcodeId;
                }];
                [[YWEquipmentManager shareManager] saveQrcodeEquipmentsWithArray:qrcodeData.equipments];
            }
        }
        if (complete) {
            if (qrcodeData) {
                complete(YWQrcodeRequestStatuSuccess);
            }else{
                complete(YWQrcodeRequestStatuNoData);
            }
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        if (complete) {
            if (response.statusCode == 404) {
                complete(YWQrcodeRequestStatuNoData);
            }else{
                complete(YWQrcodeRequestStatuFail);
            }
            
        }
    }];
}
//上传扫码日志
-(void)postQrcodeLogWithQrcodeId:(NSString *)qrcodeId qrcodeLogType:(YWQrcodeLogType)qrcodeLogType{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {return;}
    
    NSDictionary* params = @{@"qrcodeId" : qrcodeId?:@"",
                             @"type" :  @(qrcodeLogType)};
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool postQrcodeLogUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        
    }];
}
@end
